package com.wswy.wzcx.module

import com.che.libcommon.utils.AssetUtils
import com.che.libcommon.utils.JsonKit
import com.wswy.wzcx.AppContext
import com.wswy.wzcx.model.WZCity
import com.wswy.wzcx.model.resp.CityListResp
import timber.log.Timber

class CityManager {

    //private val directCityList = ArrayList<WZCity>()

    private val cityList = ArrayList<WZCity>()


    fun load(){


        AssetUtils.read2String(AppContext.getContext(),"config/city.json")?.runCatching {

                JsonKit.GSON.fromJson(this, CityListResp::class.java)?.let {

                    it.directCityList?.run {
                        cityList.addAll(this)
                    }

                    it.cityList?.forEach {province ->

                        province.list?.run {

                            forEach {
                                it.pid = province.pid
                            }
                            cityList.addAll(this)
                        }
                    }

            }
        }

//
//
//        arrayOf("340102","429006","110102","120100","440101","450202","445381").forEach {
//            Timber.e("test find --- ${findByAdCode(it)}")
//        }


    }


    /**
     * 根据高德地图adCode 查找
     */
    fun findByAdCode(adCode:String):WZCity?{


        //省直辖
        //419 429 469 659

        if (adCode.startsWith("419") ||
                adCode.startsWith("429") ||
                adCode.startsWith("469") ||
                adCode.startsWith("659")){

            //精确匹配
            return cityList.find { it.areaCode.startsWith(adCode) }

        }

        //其它地区 只匹配前4位
        val tmpCode = adCode.subSequence(0,4).toString()

        return cityList.find { it.areaCode?.startsWith(tmpCode)?:false }

    }


}